package com.zhengtoon.mctoon.conv.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bjtoon.cdpf.sdk.util.ParamCodeUtils;
import com.bjtoon.cdpf.sdk.util.RSACoder;
import com.bjtoon.framework.utils.http.HttpUtils;
import com.zhengtoon.mctoon.conv.bean.CityItem;
import com.zhengtoon.mctoon.conv.dto.param.ResultItemInfo;

import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 城市积分服务
 *
 * @author liuzhenhua
 * @since 2017-05-27
 */
public class CityIntegralUtils {
    private final static Logger log = LoggerFactory.getLogger(CityIntegralUtils.class);

    private static String appId = SysConfig.getPropertyValue("config.appId");

    private static String APP_SECRET = SysConfig.getPropertyValue("config.appSecret");

    private static String integralUrl = SysConfig.getPropertyValue("integral.url");

    private static final String PRIVATE_KEY = SysConfig.getPropertyValue("integral.privateKey");

    private static final String PUBLIC_KEY = SysConfig.getPropertyValue("integral.publicKey");

    /*

      private static String appId = "1096";

      private static String APP_SECRET = "5784ff349ef04d3eb5505e1f75220b5d";

      private static String integralUrl = "http://172.28.16.39:8081/";

      private static final String PRIVATE_KEY = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAtGcpLx+mU/WbF0kqfvpm8HOloGSbZYhRB4xMKOg3bpdsEnmCl3sj2AC/G2GaWvjBqiL+tzwiQS2Q6Sx9f1mnlQIDAQABAkEAiTlrV2AQyg6p4UWTYLEiOkcNtnqwxcOyNzad/APfnmufpD0w6GzA9YcHeG8EPMX9AphwMR0fgHStnjtaYG3GYQIhAPjFWwBEkgHiPbpmiFnDWKJz/3xYH9b1BaixpDRb52g5AiEAuaU0tU8jUZ06rmUgLXwikeu/FEh/h9w7JMCZUP3QYj0CIGZj5Gah0m6QDdQQq4I2kt6aW8d0BfbVdnTOWMVsJjyRAiBs7BWE263pUMsBT6wVg+P0odE24WKSIBFDew15i7IcMQIhAIlzfTxoF9euIe+pc+SW0nqaeRDG0DmmReb+4BPKBSSS";

      private static final String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOJVYSbEAHDBBD4YqIhF3Ovt0tbeMylCLGkWr/pYEIR/dEsyEG1j5adVytJwdnBs1MzN8rWHyyFvwd4QeW/YkhMCAwEAAQ==";

      */
    private static final String INTEGRAL_ITEMS_URL = "score/queryIntegralItems";

    private static final String INTEGRAL_COMMIT_URL = "score/commitIntegral";

    /**
     * 调用添加积分接口,获取积分和实名状态
     *
     * @param userId userid
     * @param itemId 事项ID
     * @return java.lang.Boolean
     * @author 赵康峰
     */
    public static Boolean addCityIntegral(String userId, String itemId) {

        try {
            String queryIntegralUrl = integralUrl + INTEGRAL_COMMIT_URL;

            JSONObject json = new JSONObject();
            json.put("appId", appId);
            json.put("userId", userId);
            json.put("itemId", itemId);

            log.info("调用添加积分接口加密前参数：" + json.toJSONString());
            String itemEncrypt = ParamCodeUtils.encrypt(json.toJSONString(), APP_SECRET);

            String sign = RSACoder.sign(json.toJSONString().getBytes(), PRIVATE_KEY);

            Map<String, String> paramsMap = new HashedMap();
            paramsMap.put("itemEncrypt", itemEncrypt);
            paramsMap.put("sign", sign);

            String response = HttpUtils.syncFormPostString(queryIntegralUrl, null, paramsMap);

            log.info("添加城市积分服务返回===:" + response);

            JSONObject jsonObject = JSON.parseObject(response);
            String metaString = jsonObject.getString("meta");
            JSONObject metaJsonObject = JSON.parseObject(metaString);
            String code = metaJsonObject.getString("code");
            if (code.equals("0")) {
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("调用添加积分接口发生异常", e);
            return false;
        }
    }


    /**
     * 获取积分配置
     *
     * @return java.lang.String
     * @author 赵康峰
     */
    public static List<CityItem> getCityIntegralConfig() {

        try {
            String queryIntegralUrl = integralUrl + INTEGRAL_ITEMS_URL;

            JSONObject json = new JSONObject();
            json.put("appId", appId);

            log.info("调用获取积分配置方法加密前参数：" + json.toJSONString());
            String itemEncrypt = ParamCodeUtils.encrypt(json.toJSONString(), APP_SECRET);

            String sign = RSACoder.sign(json.toJSONString().getBytes(), PRIVATE_KEY);

            Map<String, String> paramsMap = new HashedMap();
            paramsMap.put("itemEncrypt", itemEncrypt);
            paramsMap.put("sign", sign);

            String response = HttpUtils.syncGetString(queryIntegralUrl, null, paramsMap);

            log.info("获取积分字典积分服务返回===:" + response);

            JSONObject jsonObject = JSON.parseObject(response);

            ResultItemInfo resultItemInfo = JSON.parseObject(jsonObject.getString("data").toString(), new TypeReference<ResultItemInfo>() {
            });

            String resultStr = ParamCodeUtils.resolveCodeForStr(resultItemInfo.getResultItem(), APP_SECRET);

            boolean verfySuccess = RSACoder.verify(resultStr.getBytes(), PUBLIC_KEY, resultItemInfo.getSign());

            if (verfySuccess) {
                List<CityItem> result = JSON.parseObject(resultStr, new TypeReference<List<CityItem>>() {
                });
                return result;
            }

            return null;
        } catch (Exception e) {
            log.error("获取积分配置异常", e);
            return null;
        }
    }

    /**
     * 根据itemId获取配置项
     *
     * @param itemId
     * @return
     */
    public static CityItem getCityInteralDetailByItemId(Integer itemId) {

        List<CityItem> cityItemList = getCityIntegralConfig();
        for (CityItem item : cityItemList) {
            if (item.getId().equals(itemId)) {
                return item;
            }
        }

        return null;
    }


    public static void main(String[] args) throws IOException {
        List<CityItem> list = getCityIntegralConfig();
        System.out.println(list);

        System.out.println(getCityInteralDetailByItemId(1));

        /*
        Map<String, String> paramsMap = new HashedMap();
        paramsMap.put("itemEncrypt", "qPVKsBxyIgs-hdVHBacaJQdJYZ0ROqDY");
        paramsMap.put("sign", "b3ftveAGb9oE+6iFYyxzB0jz2/TCzEmGgDQU7A+E5vlzJCr7kqOBtB7dayGUnaRs9UblpUtqlo8VtXaOGfmwWw==");
        String response = HttpUtils.syncGetString("http://t100cityintegral.zhengtoon.com/score/queryIntegralItems", null, paramsMap);
        String response2 = HttpUtils.syncGetString("http://t100cityintegral.zhengtoon.com/score/queryIntegralItems?itemEncrypt=qPVKsBxyIgs-hdVHBacaJQdJYZ0ROqDY&sign=b3ftveAGb9oE%2B6iFYyxzB0jz2%2FTCzEmGgDQU7A%2BE5vlzJCr7kqOBtB7dayGUnaRs9UblpUtqlo8VtXaOGfmwWw%3D%3D");
        System.out.println(response);
        System.out.println(response2);


        LinkedHashMap<String, String> queryIntegralParam = new LinkedHashMap<>();
        queryIntegralParam.put("sign", "b3ftveAGb9oE+6iFYyxzB0jz2/TCzEmGgDQU7A+E5vlzJCr7kqOBtB7dayGUnaRs9UblpUtqlo8VtXaOGfmwWw==");
        queryIntegralParam.put("itemEncrypt", "qPVKsBxyIgs-hdVHBacaJQdJYZ0ROqDY");
        String itemJson = HttpXmlClient.httpGet("http://t100cityintegral.zhengtoon.com/score/queryIntegralItems", queryIntegralParam);
        System.out.println(itemJson);
        */
    }

}
